Introduction to Python

If you want to learn just enough Python you will want to focus on three things: 1) Saving Data 2) Manipulating and Comparing Data 3) Reusing code

In order to this you will be learning about variables, data types, methods, and functions. But first, lets learn how to mess up and recover.

Indentation

The mistake that is most common in Python is having bad indentation.

In [7]:
print "Hi Everyone.  Nice to meet you, even this early."
print "You can run this code by clicking on the 'play' button above."
print "Ater you run this code, put some spaces before the second line."
Hi Everyone.  Nice to meet you, even this early.
You can run this code by clicking on the 'play' button above.
Ater you run this code, put some spaces before the second line.

Variables

In order to save data for later use you create a variable. Luckily in Python "creating" a variables is as simple as coming up with a name and assigning a value. So:

msg1 = "Good morning" msg2 = "Good afternoon" msg3 = "Good evening" gpa = 3.21 xxyyzz = 5.23

are all examples of variables.

In [1]:
msg1 = "Good morning"
msg2 = "Good afternoon"
msg3 = "Good evening"
gpa = 3.21
xxyyzz = 5.23
print msg1
print msg2
print msg3
print gpa
print xxyyzz
Good morning
Good afternoon
Good evening
3.21
5.23

Data Types

We will talk about four different data types that you use in Python: (Single-ish Values) Numbers -- Integers, Floating Point Numbers, Complex Numbers Strings -- Consecutive characters enclosed in quotes

(Collections) Lists -- A set of data enclosed in [] where elements are separated by commas.

Tuples -- Similar to Lists, but elements are enclosed in () and can not be changed.

Dictionary -- Again, similar to Lists but elements are enclosed in {} and accessed using a key/value pair.

Numbers

Clearly sometimes you will want to manipuate your data. You can do simple things like add, subtract, multipy, divide, or even find the remainder.

In [8]:
age = 53
print age
print age + 2 
print age - 3
print age * 5
print age / 6
print age % 6
53
55
50
265
8
5

This code is very handy for learning about the operators AND experiencing a second common error in new programmers. Usually if you are bothering to perform an operation, you want to save the value somewhere. Lets look at that same code again, but this time with an assignment statement.

In [9]:
age = 53
print age
age = age + 2    #This is the same as age+=2
print age
age = age - 3    #This is the same as age-=3
print age
age = age * 5    #This is the same as age*=5
print age
age = age / 6    #This is the same as age/=6
print age
age = age % 6    #This is the same as age%=6
print age
53
55
52
260
43
1

Strings

Strings are used ALL THE TIME in Python. Strings are enclosed in quotes. Python treats single quotes the same as double quotes (but be consistent).

Double quotes allow you to enclose single quotes.

There are also triple double quotes """...""" They allow you to write strings that span multiple lines.

There are many, many built-in functionalities that you will eventually learn. It is impossible to cover (and remember) them all in one sitting.

Accessing parts of a String

You can access an entire string variable, or just parts of it. Square brackets are used to specify the index of the data you want. (Indices always start at 0.)

In [10]:
message = "Hello Everyone"
print "The first letter: ", message[0]
print "The 2nd through 9th letters: ", message[1:10]
print "The last letter is ", message[-1]
The first letter]:  H
The 2nd through 9th letters:  ello Ever
The last letter is  e

String Operators

String operators are special bits of code that ONLY WORK ON STRINGS. So while a "+" will add two numbers, it will concatenate Strings instead of adding them.

  • Concatenation - Adds values on either side of the operator

  • Repetition - Creates new strings, concatenating multiple copies of the same string

[] Slice - Gives the character from the given index

[ : ] Range Slice - Gives the characters from the given range

in Membership - Returns true if a character exists in the given string

not in Membership - Returns true if a character does not exist in the given string

In [11]:
a = "Hello"
b = "Python"
print a + b
print a * 5
print "Is H in Hello?", "H" in a
print "Is z in Hello?", "z" in a
print "Is H **NOT** in Hello?", "H" not in a
print "Is z **NOT** in Hello?", "z" not in a

print b[-1]
print b[-2]
print b[-6]
HelloPython
HelloHelloHelloHelloHello
Is H in Hello? True
Is z in Hello? False
Is H **NOT** in Hello? False
Is z **NOT** in Hello? True
n
o
P

String Methods

String methods are similar to operators in that they manipulate data, but they are used very differently. Methods use the DOT NOTATION. This means that you put the name of the variable, a dot ("."), the name of the method, and then parentheses.

In [14]:
"123".isdigit()
Out[14]:
True
In [15]:
"one".isdigit()
Out[15]:
False

Sometimes you need to additional information to get a method to work. This information is called a PARAMETER. Parameters are extra pieces of information that are needed to figure out the desired answer.

For instance, one useful method is count, it returns the number of times a substring shows up in a variable. If you want the count method to return something, you better tell it what you are looking for.

In [16]:
a = "Hello Everyone" 
print a.count('e')
print a.count('o')
print a.count('z')
3
2
0

Here are some additional String methods: find(), lfind(), rfind(), index(), isalnum(), isalpha(), isdigit(), len(), strip, lstrip(), rstrip(), split()

In [ ]:
str = "Value 1, Value 2, Value 3, Value 4";
print str.split( );
print str.split(',');

Lists

The value returned by split() is a list. The list is a versatile data type. It is a sequence of comma-separated values encased by square brackets. Items in a list do not have to be of the same type.

In [18]:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
print me
print you
['Colleen', 'van Lent', 40, 'F']
['Bob', 'McCarthy', 50, 'M']
In [20]:
for info in me:
    print info            #Try putting a comma after the word info
Colleen van Lent 40 F
In [21]:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
people = [you, me]
print people
[['Bob', 'McCarthy', 50, 'M'], ['Colleen', 'van Lent', 40, 'F']]
In [26]:
print people[0]           #Change the 0 to a 1, and then a 2
['Colleen', 'van Lent', 40, 'F']

Built-in List Functions and Methods

Lists have a number of functions and methods associated with them. Some functions include: len(list) max(list) min(list) list(seq)

Some of the methods are: count(), index(obj)

Some list methods are in-place. This means that the lists are changed, but the methods don't "return" anything. These include sort(), reverse(), insert(), append(), and remove.

In [30]:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
her = ["Sally", "James", 25, 'Unknown']
him = ["John", "Doe", 18, 'M']
people = [me, you, her, him]
print people



print "\nList Functions \n"
print "The length of the full list is " ,len(people)
print "The max of the full list is" ,max(people)
print "The min of the full list is" ,min(people)



print "\nList Methods\n"
print "How many times does Colleen appear?", people.count('Colleen')
print "How many times does Colleen list appear?", people.count(me)


print "\nThe initial list is", people
people.sort() 
print "Now it is sorted", people

print "\nThe initial list is", people
people.reverse()
print "Now it has been reversed", people

print "\nThe initial list is", people
people.append(['Becca', 'van Lent', 5, 'F'])
print people

print "\nThe initial list is", people
people.insert(2, ['Chris', 'van Lent', 7, 'M'])
print people
[['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M']]

List Functions 

The length of the full list is  4
The max of the full list is ['Sally', 'James', 25, 'Unknown']
The min of the full list is ['Bob', 'McCarthy', 50, 'M']

List Methods

How many times does Colleen appear? 0
How many times does Colleen list appear? 1

The initial list is [['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M']]
Now it is sorted [['Bob', 'McCarthy', 50, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['John', 'Doe', 18, 'M'], ['Sally', 'James', 25, 'Unknown']]

The initial list is [['Bob', 'McCarthy', 50, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['John', 'Doe', 18, 'M'], ['Sally', 'James', 25, 'Unknown']]
Now it has been reversed [['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M']]

The initial list is [['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M']]
[['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Becca', 'van Lent', 5, 'F']]

The initial list is [['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Becca', 'van Lent', 5, 'F']]
[['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Chris', 'van Lent', 7, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Becca', 'van Lent', 5, 'F']]

Now what?

Lets do a little input using the raw_input() function.

In [ ]:
message = raw_input("Enter your input: ")

print message
print message.find("Colleen")
print message.count("l")
print message.index(" ")
print message.rfind(" ")

Functions and methods are great way to reuse code. Someone wrote some code and you (awesomely) get to use it over and over again. But you can write your own code for reuse as well. One way to do that is to write your own functions. Another way is to use loops.

Flow of Control

The real power of computing is selection and repetition. Selection is when you use comparison operators to direct which path the program should take. Repetition is when code is executed multiple times.

In [37]:
num_cookies = 5
while num_cookies > 0:
    print "Yum!!"
    num_cookies -=1                                    #Don't unindent this code!!!
    print "Only " + str(num_cookies) + " left"         #Unindent this code
print "I am full now."
 Yum!!
Only 4 left
Yum!!
Only 3 left
Yum!!
Only 2 left
Yum!!
Only 1 left
Yum!!
Only 0 left
I am full now.

The indentation is VERY, VERY important. You must be consistent, you can't switch back and forth between tabs or individual spaces.

The other thing you need to be VERY worried about is the possibility of infinite loops. Go back up and change the code to num_cookies = 0 or add one instead of subtracting one.

if statements

You can use if statements to control which code is executed.

In [45]:
age = raw_input("Enter your age: ")
age = int(age)
if age < 18:
    print "Minor"
Enter your age: 11
Minor
In [47]:
age = raw_input("Enter your age: ")
age = int(age)
if age < 18:
    print "Minor"
else:
    print "Adult"
Enter your age: 34
Adult
In [49]:
age = raw_input("Enter your age: ")
age = int(age)
if age < 18:                         #Option 1
    print "Minor"
elif age > 100:                      #Option 2
    print "Centenarian"
elif age > 65:                       #Option 3
    print "Senior"
else:                                #Option 4
    print "Adult"
Enter your age: 56
Adult

Looping

Did you notice the colon : in the if statements? The colon signifies that a block of code is coming. That block of code is indented. You also use the colon when writing loops.

while loop

The while loop will execute the block of code over and over until the conditional statement after the word "while" is true.

In [50]:
num = 0
while num <=10:
    if num % 2 == 0:
        print num
    num +=1
0
2
4
6
8
10

for loop

The for loop is typically used in two situations. The first is when you know how many time you want to execute a loop. The second is when you want to loop through a collection.

In [51]:
for x in range(0, 3):
    print x
0
1
2
In [52]:
for info in me:
    print info            #Try putting a comma after the word info
Colleen
van Lent
40
F
In [58]:
list_of_lists = [ [1, 2, 3, 4], [5, 6], [7, 8, 9]]
for list in list_of_lists:
    for x in list:
        print x                            #Add another comma here
    #print "\n"
1
2
3
4
5
6
7
8
9

Loops and lists

In [59]:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
her = ["Sally", "James", 25, 'Unknown']
him = ["John", "Doe", 18, 'M']
people = [me, you, her, him]
for  i in range(len(people)):
    print i, people[i]
0 ['Colleen', 'van Lent', 40, 'F']
1 ['Bob', 'McCarthy', 50, 'M']
2 ['Sally', 'James', 25, 'Unknown']
3 ['John', 'Doe', 18, 'M']

Functions

We have already used functions in this tutorial. A function is a block of reusable code that is used to perform a single (albeit possibly complex) task. Functions allow for code reuse and also allow you to work better as a team. The process of defining a function is as follows:

1) Function blocks begin with the keyword def followed by the function name, parentheses ( ), and colon def myFunction():

2) Any input parameters or arguments should be placed within these parentheses. def printMeALot(msg, times):

3) The code block within every function is indented. def printMeALot(msg, times): for i in range(times): print msg

4) Any return statements will cause an exit from the a function

5) A return statement can pass an expression back to the caller. A return statement with no arguments is the same as return None.

In [60]:
def printMeALot(msg, times):
    for i in range(times):
        print msg
            
printMeALot("I am the greatest", 10)
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest

Using what you have

Later you will learn more about using code from others. Below I have two examples of some Python code that uses the Beautiful Soup package. Beautiful soup can parse a webpage, letting you parse the information.

Lets just focus on the code I hope you now can make small changes to. (Start with the for loops.) Can you identify the variables? The loops? Can you find string methods?

In [67]:
import requests
from bs4 import BeautifulSoup
 
base_url = 'http://www.nytimes.com'
r = requests.get(base_url)
soup = BeautifulSoup(r.text)


for story_heading in soup.find_all(class_="story-heading"): 
    if story_heading.a: 
        print(story_heading.a.text.replace("\n", " ").strip())
    else: 
        print(story_heading.contents[0].strip())
Sanders’s West Virginia Victory Prolongs Race With Clinton
Clinton, in Shift to Left, Favors Wider Access to Medicare
Ryan Revives Lost Washington Art of Intraparty Jousting
Both Disliked, Clinton and Trump Accentuate the Negatives
In Clinton, U.F.O. Enthusiasts See End of a U.S. Cover-Up
Obama’s Plans in Hiroshima Raise Ghosts of History
Obama to Be First Sitting President to Visit Hiroshima
Global Warming Seen as Lit Match in Northern Fires
Your Evening Briefing
A Secret Section of Central Park Reopens
It’s a Tough Job Market for the Young Without Degrees
Government Must Play a Role Again in Job Creation
Transgender Fight May Hinge On Reach of a 1964 Law
A Filipino ‘Donald Trump’ Inspires Fear, and Praise
The Full-Bodied Joy of Students Who Got a Late Start
Staples and Office Depot End $6.3 Billion Merger Plan
Bangladesh Tense After Opposition Leader Is Executed
Seller-Financed Home Sales Get Federal Scrutiny
Turkey’s President Fails to Silence German Publisher
Uber Agrees to Guild for New York Drivers
Stephen Curry’s 17-Point Overtime: Shot by Shot
Gay Rights Landmarks, Beyond the Stonewall Inn
Spring in Paris, My New Home, After the Siege
What Mr. Obama Can Say at Hiroshima
Editorial: A Soldier’s Challenge to the President
Brooks: Putting Grit in Its Place
China's Middle-Class Anxieties
Campaign Stops: The Women Who Like Donald Trump
Op-Ed: Is This the End of the Religious Right?
Chewing the Fat With Obama and Bryan Cranston: Notes From the Oval Office
Starry, Starry Night: A Photo Shoot
Chewing the Fat With Obama and Bryan Cranston: Notes From the Oval Office
Play Today’s Puzzle
Play Today’s Puzzle
Words From Sinatra
Notes on an Obama and Bryan Cranston Sit-Down
An Experimental Living Room in New York City
Op-Ed: Why Dark Money Is Bad Business
Films From Middle East Have Big Year at Cannes
Review: Portraits of Vietnam in Love and War
Will Regulating E-Cigarettes Mean Fewer Will Quit?
Lens: Reclaiming a Photographic Narrative
Fixes: Using Tweets to Speed Up Organ Donation
A Window Into the Workings of Zika
Talks With John Updike, Toni Morrison and More
Couch: Of Dating and Diplomacy
‘The Good Wife’ Ends With No Easy Answers
Obama’s Visit Raises Ghosts of Hiroshima
Brazilian Speaker, in About-Face, Won’t Annul Dilma Rousseff’s Impeachment
Romania Takes Step Toward Restitution to Holocaust Survivors
Senator Demands Answers From Facebook on Claims of ‘Trending’ List Bias
Puerto Rico’s Fiscal Fiasco Is a Harbinger of Mainland Woes
Clinton Son-in-Law’s Firm Is Said to Close Greece Hedge Fund
The Stone: Trump, Truth and the Power of Contradiction
Editorial: A Better, Not Fatter, Defense Budget
Charles M. Blow: G.O.P. Has Only Itself to Blame
Two Fatally Stabbed; Attacker Is Killed at Mall in Massachusetts
West Point Won’t Punish Cadets in Raised-Fist Photo
USA Today Cuts Ties With Crossword Editor After Plagiarism Scandal
Senator Demands Answers From Facebook on Claims of ‘Trending’ List Bias
As ‘Sextortion’ Proliferates, Victims Find Precarious Place in Legal System
Uber Recognizes New York Drivers’ Group, Short of a Union
Michael S. Harper, Poet With a Jazz Pulse, Dies at 78
Prince’s Doctor Arrived With Test Results Only to Find Him Dead
George Carlin’s Belongings Find New Home at National Comedy Center
Bernie Sanders Wins West Virginia, Prolonging Race With Hillary Clinton
First Draft: Donald Trump’s Campaign Trail May Take Detour to Scotland
First Draft: Hillary Clinton Backs Income Limits on Parents’ Costs for Child Care
On Beauty: Skincare Advice From a Budapest-Based Beauty Founder
List of Five: Colin Hanks Learns the Importance of Fashion From Tim Gunn
The Forgotten Designer Behind Some of Fashion’s Biggest Trends
Crowe and Gosling in a Comedy? Seriously
Review: Health Care Bureaucracy Runs Amok in ‘A Monster With a Thousand Heads’
‘King of Jazz’ Is Back, Burnished for Movie Fans
Mistrial Declared in Racketeering Case Against Reputed Mafia Leader
Court Vacates Long Island Teacher’s Evaluation Tied to Test Scores
Cuomo Distances Himself From Lobbyist at Center of Inquiry
On Pro Basketball: Stephen Curry Turns the Amazing Into the Everyday and Raises the Bar, Over and Over
Stephen Curry Is M.V.P., and This Time It’s Unanimous
Stephen Curry’s 17-Point Overtime: Shot by Shot
Rhiannon Giddens to Replace Audra McDonald During ‘Shuffle Along’ Hiatus
MCC Theater to Present the Musical ‘Ride the Cyclone’ and a Matthew Perry Play
Joe Allen, Broadway’s Quiet Man
Global Warming Cited as Wildfires Increase in Fragile Boreal Forest
Kepler Finds 1,284 New Planets
Study Casts Doubt on Theory That Legal Hunting Reduces Poaching
Anne Deborah Atai-Omoruto, Who Helped Lead Ebola Fight in Liberia, Dies at 59
Michael S. Harper, Poet With a Jazz Pulse, Dies at 78
Ramón Carlín, Casual Sailor Who Won a Round-the-World Race, Dies at 92
Chewing the Fat With Obama and Bryan Cranston: Notes From the Oval Office
Submit Questions for Ilene Chaiken of ‘Empire’
What’s on TV Tuesday
Anne Deborah Atai-Omoruto, Who Helped Lead Ebola Fight in Liberia, Dies at 59
Addicts Who Can’t Find Painkillers Turn to Anti-Diarrhea Drugs
The New Health Care: E-Cigarettes Are Safer, but Not Exactly Safe
Essay: Spring in Paris, My Adopted City, After the Siege
Update: Where to Go in Europe, and How to Stay Safe
In Transit: When ‘Suspicious’ Activity on Flights Really Isn’t
Bookends: What’s the Best Book Written About Siblings?
Nonfiction: ‘How Women Decide,’ by Therese Huston
Nonfiction: ‘You May Also Like’ and ‘Pretentiousness: Why It Matters’
It’s a Tough Job Market for the Young Without College Degrees
At Cornell, the College Daily Will No Longer Be Daily
Editorial: Guess Who’s Taking Remedial Classes
Restaurant Review: Looks Aren’t Everything at Café Altro Paradiso
Joe Allen, Broadway’s Quiet Man
Fried Chicken With a German Accent
Opinion: Why You Can’t Lose Weight on a Diet
Editorial | Locked Out of Society: Labels Like ‘Felon’ Are an Unfair Life Sentence
Frank Bruni: Sex and the Singular Pol
Brooklyn on the North Fork
Exclusive: Old Meets New in Sag Harbor
International Real Estate: House Hunting in ... Wales
The 2016 Race: No, the Battleground States Are Not a Terrific Fit for Donald Trump
The 2016 Race: Voters’ Fears About Trump May Outweigh Wish for Change
The New Health Care: E-Cigarettes Are Safer, but Not Exactly Safe
First Words: What Do Our Online Avatars Reveal About Us?
On Money: Bubble Indemnity
Social Capital: The Blue-Velvet Vapelord: On Perfume Genius’s Twitter
Takata Estimates a Loss of $120 Million, Citing Recalls
Driven: Video Review: Kia Sportage Gets a Stylish Makeover
Head of Fiat Chrysler Sees Self-Driving Cars in Five Years, Not 20
On Beauty: Skincare Advice From a Budapest-Based Beauty Founder
A Performance Project That Brings Some Mystery to the Glass House
A Spring Asparagus Dish From London’s Beloved River Café
Chewing the Fat With Obama and Bryan Cranston: Notes From the Oval Office
Starry, Starry Night: A Photo Shoot
Book Club: Times Insider Book Club: More on College Admissions Mania
Christopher Jackson of ‘Hamilton,’ at Home in the Bronx
Search for Homes for Sale or Rent
Sell Your Home
Old Meets New in Sag Harbor
In [68]:
import requests
from bs4 import BeautifulSoup
 
base_url = 'https://www.michigandaily.com/section/opinion'
r = requests.get(base_url)

soup = BeautifulSoup(r.text)

for story_heading in soup.find_all(class_="pane-most-read-panel-pane-1"): 
    for links in story_heading.find_all(class_="field-content"):
        if links.a: 
            print("\n"+links.a.text.replace("\n", " ").strip())
        else: 
            print("\n"+links.contents[0].strip())
Romero finally feeling healthy

Lawrence leaves her footprints on the basepaths

CGI makes ‘The Jungle Book’ compelling

Senior class leads Wolverines to ninth straight Big Ten title

Wolverines prepare for Big Ten Outdoor Championships
In [ ]: